package com.example.demo.tree;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TreeTool {
    private boolean countIdPath = false;
    private boolean countCodePath = false;
    private boolean countNamePath = false;
    public TreeTool() {}

    public void setCountCodePath(boolean countCodePath) {
        this.countCodePath = countCodePath;
    }

    public void setCountNamePath(boolean countNamePath) {
        this.countNamePath = countNamePath;
    }

    public void setCountIdPath(boolean countIdPath) {
        this.countIdPath = countIdPath;
    }

    public List<TreeNode> tree(List<TreeNode> list, String rootId) {
        if (list == null) {
            return null;
        }
        List<TreeNode> result = new ArrayList<>();
        Map<String, List<TreeNode>> map = new HashMap<>();
        for (TreeNode t : list) {
            String pid = t.getPid();
            String tid = t.getTid();
            if (!map.containsKey(pid)) {
                map.put(pid, new ArrayList<>());
            }
            map.get(pid).add(t);
            if (tid.equals(rootId)) {//这是根
                result.add(t);
            }
        }
        if (result.size() <= 0) {
            List<TreeNode> rootList = map.get(rootId);
            if (rootList == null || rootList.size() <= 0) {
                return null;
            }
            result.addAll(rootList);
        }
        for (TreeNode t : list) {
            String tid = t.getTid();
            if (map.containsKey(tid)) {
                List<TreeNode> treeNodes = map.get(tid);
                t.setChilren(treeNodes);
            }
        }
        return result;
    }
    public List<TreeNode> loop(List<TreeNode> list) {
        return new TreeNode(list).loopChildren();
    }
}
